package com.selenium.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.selenium.bean.FetchCorpVO;
import com.selenium.bean.FetchUserVO;
import com.selenium.bean.InitBean;
import com.worktool.RestExecutor;
import org.springframework.http.*;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.util.*;


public class ThirdpartnarServiceImp implements ThirdpartnarService{

    private static InitBean bean;

    private static RestTemplate restTemplate = RestExecutor.build();

    private static List<FetchUserVO.Mems> users = new LinkedList<>();

    public ThirdpartnarServiceImp(InitBean bean){
        this.bean = bean;
        System.err.println("cookie:"+bean.getCookie());
        System.err.println("bean:"+bean.getVo());
    }


    @Override
    public FetchCorpVO fetchCorp(String keyWord) {

        String url = StrUtil.format("https://open.work.weixin.qq.com/wwopen/developer/operate/admin/list?" +
                "lang=zh_CN&ajax=1&f=json&limit=10&offset=0&keyword={}&random={}",keyWord,Math.random());


        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, bean.getCookie());
        //httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://open.work.weixin.qq.com/wwopen/developer");

        HttpEntity requestEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.GET,requestEntity, JSONObject.class);
        //System.err.println(result.getBody());
        if(result.getStatusCode().equals(HttpStatus.OK)&& result.hasBody()){
            System.err.println("获取["+keyWord+"[数据成功");
            FetchCorpVO vo = result.getBody().getJSONObject("data").toJavaObject(FetchCorpVO.class);
            //System.err.println("请求值："+vo);
            return  vo;
        }
        System.err.println("获取["+keyWord+"[数据失败");
        return null;
    }

    @Override
    public FetchUserVO fetchUsers() {
        String url = StrUtil.format("https://work.weixin.qq.com/wework_admin/contacts/member/cache?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random={}",Math.random());


        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, bean.getCookie());
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/third/selectContacts");

        HttpEntity requestEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.POST,requestEntity, JSONObject.class);
        System.err.println(result.getBody());
        if(result.getStatusCode().equals(HttpStatus.OK)&& result.hasBody()){
            System.err.println("获取人员数据成功");
            FetchUserVO vo = result.getBody().getJSONObject("data").toJavaObject(FetchUserVO.class);
            //System.err.println("请求值："+vo);
            return  vo;
        }
        System.err.println("获取人员数据失败");
        return null;

    }

    @Override
    public void addThirdUser(FetchCorpVO vo,String key) {
        Assert.notNull(vo,"下游企业信息为空，请先获取下游企业信息");

        Assert.notEmpty(vo.getAdmin_corp_list(),"下游企业信息为空，请先获取下游企业信息");


        /**
         * 缓存人员如果是空就需要加载一遍人员
         * */
        if(users.size()<1){
            users = this.fetchUsers().getMems();
        }

        Optional<FetchUserVO.Mems> opUser = users.stream().filter(e->e.getName().equals(key)||e.getMobile().equals(key)).findFirst();

        if(opUser.isPresent()){
            FetchUserVO.Mems user = opUser.get();
            List<FetchCorpVO.StaffList> hUser = vo.getAdmin_corp_list().get(0).getStaff_list();
            //代运营一共只能设置三个，如果超过2个 直接移除第三个

            JSONArray arr = new JSONArray();

            Boolean userIs = hUser.stream().filter(e->e.getName().equals("key")).findAny().isPresent();
            //需要添加的人  在这个企业的代运营下面，直接返回
            if(userIs){
                return;
            }

            if(hUser.size()>2){
                hUser.remove(2);
            }

            for(FetchCorpVO.StaffList staffList:hUser){
                JSONObject json = new JSONObject();
                json.put("vid",staffList.getVid());
                json.put("name",staffList.getName());
                arr.add(json);
            }

            JSONObject json = new JSONObject();
            json.put("vid",user.getVid());
            json.put("name",user.getName());
            arr.add(json);
            this.addThirdUser(vo.getAdmin_corp_list().get(0).getWw_corpid(),arr);


        }
    }

    private void addThirdUser(String corpid,JSONArray arr){
        String url = StrUtil.format("https://open.work.weixin.qq.com/wwopen/developer/operate/admin/set?" +
                "lang=zh_CN&ajax=1&f=json&random={}",Math.random());

        JSONObject params = new JSONObject();

        params.put("admin_corpid",corpid);
        params.put("staff_list",arr);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, bean.getCookie());
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add("Referer","https://open.work.weixin.qq.com/wwopen/developer");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.POST,requestEntity, JSONObject.class);
        System.err.println(result.getBody());
        if(result.getStatusCode().equals(HttpStatus.OK)&& result.hasBody()&&result.getBody().containsKey("data")){
            System.err.println("添加代运营人员数据成功");
            return;
        }
        System.err.println("添加代运营人员数据失败");
    }



}
